package com.example.demo.dao;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
@Slf4j
public class StudentDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public void studenOpt() {
        jdbcTemplate.execute("create table t_stu(id int identity ,title varchar(255))");
        jdbcTemplate.update("insert into t_stu(title) values('Sam')");
        jdbcTemplate.update("insert into t_stu(title) values('Jack')");
        jdbcTemplate.queryForList("select * from t_stu").forEach(m->log.info(m.toString()));
        log.info(jdbcTemplate.queryForMap("select * from t_stu where id=1").toString());
        log.info(jdbcTemplate.queryForObject("select title from t_stu where id=1",String.class));
    }

    public void findAll() {
        RowMapper<String> row = new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getString("name");
            }
        };
        jdbcTemplate.queryForList("select id,name from t_student").forEach(m -> log.info(m.toString()));
        //jdbcTemplate.query("select id,name from t_student",row).forEach(name->log.info(name));
    }

    public void test01() {
        log.info(jdbcTemplate.queryForMap("select id,name from t_student where id=?", new Object[]{1}).toString());
    }

    public void test02() {
        log.info(jdbcTemplate.queryForObject("select name from t_student where id=?", new Object[]{1}, String.class));
    }

    public void save() {
        jdbcTemplate.update("insert into t_student(name) values(?)", new Object[]{"Tom"});
    }

    public void edit() {
        jdbcTemplate.update("update t_student set name = 'aaa' where  id=?", new Object[]{1});
    }

    public void remove() {
        jdbcTemplate.update("delete from t_student where id=?", new Object[]{2});
    }

    public void count() {
        log.info("count : {}", jdbcTemplate.queryForObject("select count(*) from t_student", Integer.class));
    }
}
